package cn.zzdt4j.console.controller;

import cn.zzdt4j.auth.model.UserInfo;
import cn.zzdt4j.auth.model.biz.permission.PermissionRespDTO;
import cn.zzdt4j.auth.model.biz.user.UserReqDTO;
import cn.zzdt4j.auth.model.biz.user.UserRespDTO;
import cn.zzdt4j.auth.security.AuthManager;
import cn.zzdt4j.auth.service.UserService;
import cn.zzdt4j.common.constant.Constants;
import cn.zzdt4j.common.model.Result;
import cn.zzdt4j.common.model.TokenInfo;
import cn.zzdt4j.config.service.biz.TenantService;
import cn.zzdt4j.server.common.base.Results;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.stream.Collectors;

import static cn.zzdt4j.auth.constant.Constants.TOKEN_VALIDITY_IN_SECONDS;
import static cn.zzdt4j.common.constant.Constants.ADMIN_USER;

/**
 * User controller
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023/11/6 12:36
 */
@RestController
@AllArgsConstructor
@RequestMapping(Constants.BASE_PATH + "/auth/users")
public class UserController {

    private final UserService userService;

    private final AuthManager authManager;

    private final TenantService tenantService;

    @PostMapping("/apply/token")
    public Result<TokenInfo> applyToken(@RequestBody UserInfo userInfo) {
        String accessToken = authManager.resolveTokenFromUser(userInfo.getUserName(), userInfo.getPassword());
        TokenInfo tokenInfo = new TokenInfo(accessToken, TOKEN_VALIDITY_IN_SECONDS);
        return Results.success(tokenInfo);
    }

    @GetMapping("/info/{username}")
    public Result<UserRespDTO> userInfo(@PathVariable("username") String username) {
        UserRespDTO userRespDTO = userService.getUser(new UserReqDTO().setUserName(username));
        if (Objects.equals(username, ADMIN_USER)) {
            userRespDTO.setResources(tenantService.listAllTenant().stream().map(each -> new PermissionRespDTO(username, each, "rw")).collect(Collectors.toList()));
            userRespDTO.setTempResources(tenantService.listAllTenant());
        }
        return Results.success(userRespDTO);
    }

}
